<template>
  <div class="role-management">
    <a-row type="flex" justify="center" align="middle">
      <a-col :span="8">
        <a-form layout="inline">
          <a-form-item label="角色名称">
            <a-input v-model="params.roleName" placeholder="请输入角色名称" allow-clear>
              <a-icon slot="prefix" type="user" />
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" icon="search" @click="onSearch">查询</a-button>
          </a-form-item>
        </a-form>
      </a-col>
      <a-col :span="6" :offset="10" style="text-align: right">
        <a-button type="primary" icon="plus" @click="onNewRole">添加角色</a-button>
      </a-col>
    </a-row>
    <a-table class="roles-table" rowKey="id" :columns="columns" :data-source="dataSource" :pagination="{
                current: params.page,
                pageSize: params.pageSize,
                total: total,
                showLessItems: true,
                onChange: onPageChange,
                onShowSizeChange: onSizeChange,
            }">
      <template v-for="col in ['name', 'enableIf', 'memo', 'updateTime']" :slot="col" slot-scope="text, record">
        <div :key="col">
          <div v-if="record.editable">
            <a-input v-if="col != 'enableIf'" style="margin: -5px 0" :value="text" @change="e => handleChange(e.target.value, record.id, col)" allow-clear />
            <a-switch v-else v-model="record.enableIf" checked-children="启用" un-checked-children="禁用" />
          </div>
          <template :disabled="editingKey !== ''" v-else>
            <span v-if="col == 'enableIf'">
              <a-badge v-if="record.enableIf" color="green" text="启用" />
              <a-badge v-else color="red" text="禁用" />
            </span>
            <span v-else>{{ text }}</span>
          </template>
        </div>
      </template>
      <template slot="operation" slot-scope="text, record">
        <a-space v-if="record.editable" :size="2">
          <a @click="() => save(record.id)">保存</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定要取消保存吗?" @confirm="cancel(record.id)">
            <a>取消</a>
          </a-popconfirm>
        </a-space>
        <a-space v-else :size="2">
          <a class="ant-dropdown-link" @click="onDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a class="ant-dropdown-link" :disabled="editingKey !== ''" @click="edit(record.id)">编辑</a>
          <a-divider type="vertical" v-if="record.enableIf" />
          <a class="ant-dropdown-link" v-if="record.enableIf" @click="onAdd(record)">添加人员</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定要删除该角色吗?" ok-text="确定" cancel-text="取消" @confirm="onConfirmDelete()">
            <a class="ant-dropdown-link" @click="onDelete(record)">删除</a>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>
    <!-- 新建角色Modal -->
    <editRole :isRoleModal="isRoleModal" :roleType="0" @cancelModal="onCancel"></editRole>
    <!-- 添加成员Modal -->
    <addMember :memberModal="isMemberModal" @cancelModal="onCancel" :roleName="nowRole.name"></addMember>
    <drawer title="角色详情" ref="drawer" :visible.sync="detailDrawer" @getList="getList">
      <roleDetail slot="content" :role="nowRole"></roleDetail>
    </drawer>
  </div>
</template>

<script>
import editRole from '../modal/EditRoleModal';
import addMember from '../modal/addMemberModal.vue';
import { roleList, updateRole, deleteRole, addMemeber } from '@/services/role';
import { transferDate } from '@/utils/util';
import Drawer from '@/pages/components/drawer'
import roleDetail from './characterDetails.vue';
export default {
  name: 'roleManagement',
  components: { editRole, addMember, Drawer, roleDetail },
  props: ['apply'],
  data () {
    return {
      detailDrawer: false,
      params: {
        roleName: '',
        page: 1,
        pageSize: 10,
      },
      total: 0,
      columns: [
        {
          title: '角色名称',
          dataIndex: 'name',
          width: '20%',
          scopedSlots: { customRender: 'name' },
        },
        {
          title: '状态',
          dataIndex: 'enableIf',
          width: '10%',
          scopedSlots: { customRender: 'enableIf' },
        },
        {
          title: '角色描述',
          dataIndex: 'memo',
          width: '35%',
          scopedSlots: { customRender: 'memo' },
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          width: '15%',
          scopedSlots: { customRender: 'updateTime' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '20%',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      dataSource: [],
      editingKey: '',
      isRoleModal: false,
      isMemberModal: false,
      nowRole: {},
      cacheData: [],
    };
  },
  watch: {
    apply: {
      handler (val) {
        if (val) {
          this.getRoleList(this.params);
        }
      }
    }
  },
  methods: {
    onSearch () {
      this.getRoleList(this.params);
    },
    onNewRole () {
      this.isRoleModal = true;
    },
    getList () {
      this.getRoleList(this.params);
    },
    onAdd (role) {
      this.nowRole = role;
      this.isMemberModal = true;
    },
    onDelete (role) {
      this.nowRole = role;
    },
    onDetail (role) {
      this.detailDrawer = true;
      this.nowRole = role;
    },
    onCancel (result) {
      let { modal, data, success } = result;
      if (modal == '添加人员') {
        if (success == 'ok') {
          let params = {
            roleId: this.nowRole.id,
            userIds: data.memberList.toString(),
            status: 0,
          };
          addMemeber(params).then(res => {
            let { code, data, msg } = res.data;
            if (code == 200) {
              this.$message.success(msg);
            } else {
              this.$message.error(msg);
            }
          });
        }
        this.isMemberModal = false;
      } else if (modal == '新建角色') {
        if (success == 'ok') {
          this.addRole(data);
        }
        this.isRoleModal = false;
      }
    },
    // 可编辑行表格
    handleChange (value, key, column) {
      const newData = [...this.dataSource];
      const target = newData.filter(item => key === item.id)[0];
      if (target) {
        target[column] = value;
        this.dataSource = newData;
      }
    },
    edit (key) {
      this.nowRole.id = key;
      const newData = [...this.dataSource];
      const target = newData.filter(item => key === item.id)[0];
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.dataSource = newData;
      }
    },
    save (key) {
      const newData = [...this.dataSource];
      this.cacheData = this.dataSource.map(item => ({ ...item }));
      const newCacheData = [...this.cacheData];
      const target = newData.filter(item => key === item.id)[0];
      const targetCache = newCacheData.filter(item => key === item.id)[0];
      if (target && targetCache) {
        delete target.editable;
        this.dataSource = newData;
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      this.editingKey = '';
      let { enableIf, name, memo } = target;
      const params = { enableIf, name, memo, id: key };
      this.addRole(params);
    },
    cancel (key) {
      const newData = [...this.dataSource];
      const target = newData.filter(item => key === item.id)[0];
      this.editingKey = '';
      if (target) {
        Object.assign(target, this.cacheData.filter(item => key === item.id)[0]);
        delete target.editable;
        this.dataSource = newData;
      }
    },
    onConfirmDelete () {
      deleteRole({ id: this.nowRole.id }).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.$message.success(msg);
        } else {
          this.$message.error(msg);
        }
        this.getRoleList(this.params);
      });
    },
    /**
     * @description: 分页
     * @param {*} page
     * @param {*} pageSize
     * @return {*}
     */
    onPageChange (page, pageSize) {
      this.params.page = page;
      this.params.pageSize = pageSize;
      this.getRoleList(this.params);
    },
    onSizeChange (current, size) {
      this.params.page = 1;
      this.params.pageSize = size;
      this.getRoleList(this.params);
    },
    /**
     * @description: 获取角色分页列表
     * @param {*}
     * @return {*}
     */
    getRoleList () {
      let { roleName, page, pageSize } = this.params;
      let params = {
        name: roleName,
        pageNum: page,
        pageSize,
      };
      roleList(params).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.total = data.totalElements;
          this.dataSource = data.content;
          for (var i of this.dataSource) {
            i.updateTime = transferDate(i.updateTime, 2);
          }
        } else {
          this.$message.error(msg);
        }
      });
    },
    /**
     * @description: 添加/修改角色
     * @param {*} params
     * @return {*}
     */
    addRole (params) {
      updateRole(params).then(res => {
        this.getRoleList(this.params);
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.$message.success(msg);
        } else {
          this.$message.error(msg);
        }
      });
    },
  },
  created () {
    this.getRoleList(this.params);
  },
};
</script>

<style scoped lang="less">
.role-management {
  background: #fff;
  padding: 24px;
}
.roles-table {
  margin-top: 24px;
}
.role-mandetail {
  /deep/ .ant-drawer-body {
    padding: 0 24px;
  }
}
</style>
